package com.zhixun.mobile.modules.jiujiudevice.device.task;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.boxin.ims.modules.jiujiudevice.entity.JiuDevice;
import com.boxin.ims.modules.jiujiudevice.entity.JiuOrderRecord;
import com.boxin.ims.modules.jiujiudevice.entity.JiuSn;
import com.boxin.ims.modules.jiujiudevice.service.JiuDeviceService;
import com.boxin.ims.modules.jiujiudevice.service.JiuOrderRecordService;
import com.thinkgem.jeesite.common.utils.JedisUtils;

/**
 * 
 * @author sxh
 * @date 2018年11月17日 上午11:13:47
 * @function <p> 自动结束订单的线程，设备突然断电结束订单,目前还没有使用</p>
 *
 */
@Service
public class AutoCloseOrderThread implements Runnable{
	
	
	private JiuDeviceService jiuDeviceService;
	private JiuOrderRecordService jiuOrderRecordService;
	
	@Autowired
	public AutoCloseOrderThread(JiuDeviceService jiuDeviceService,JiuOrderRecordService jiuOrderRecordService) {
		// TODO Auto-generated constructor stub
		this.jiuDeviceService = jiuDeviceService;
		this.jiuOrderRecordService = jiuOrderRecordService;
		if(null != jiuDeviceService && jiuOrderRecordService != null){
			new Thread(this).start();
		}
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		System.out.println("自动结束断电设备的订单线程已经启动");
		while(true){
			System.out.println("自动结束断电设备的又开始启动了");
			List<JiuDevice> jiuDeviceList = jiuDeviceService.findAll();
			if(jiuDeviceList != null){
				for (int i = 0; i < jiuDeviceList.size(); i++) {
					JiuDevice jiu = jiuDeviceList.get(i);
					if(JedisUtils.exists(JiuSn.DEVICE_EXSIT+"_"+jiu.getSn())){
						//得到设备断电前的时间
						Long time = (Long) JedisUtils.getObject(JiuSn.DEVICE_EXSIT+"_"+jiu.getSn());
						System.out.println(jiu.getSn()+"设备时间================================!!!!>"+time);
						Long currentTime = System.currentTimeMillis();
						Long min = (currentTime - time)/1000;
						System.out.println("设备的使用秒数=====================》"+min+" s");
						//超过30秒还是没有数据 就结束订单
						if(min > 20){
							  if(JedisUtils.exists(JiuDevice.MEMBER_USE_DEVICE_CACHE_KEY+"_"+jiu.getSn())){
		                            	String orderNo = JedisUtils.get(JiuDevice.MEMBER_USE_DEVICE_CACHE_KEY+"_"+jiu.getSn());
		                            	JiuOrderRecord jiuOrder =jiuOrderRecordService.getByOrderNo(orderNo);
		                            	jiuOrder.setEndTime(new Date());
		                            	jiuOrderRecordService.save(jiuOrder);
		                        }	
						}
                           
				}
			  }
			}
			try {
				Thread.sleep(1000*10);
			} catch (InterruptedException e) {
				System.err.println("清除过期订单的线程被中断");
				e.printStackTrace();
			}
			
		}
	}
}

